package leetcode.code0647;

public class Solution extends Solution647 {

	private int sharpLen;
	private int len;

	@Override
	public int countSubstrings(String s) {
		char[] sharp = this.sharp(s);
		int[] radius = new int[sharpLen];
		int center = 0;
		int range = 0;
		int ans = 0;
		for (int i = 0; i < sharpLen; i++) {
			radius[i] = i < range ? Math.min(range - i, radius[(center << 1) - i]) : 1;
			while (i + radius[i] < sharpLen && i - radius[i] > -1 && sharp[i + radius[i]] == sharp[i - radius[i]]) {
				radius[i]++;
			}
			if ((i & 1) == 1) {// '#'
				ans += (radius[i] / 2);
			} else {
				ans += (radius[i] & 1) == 0 ? (radius[i] / 2) : (radius[i] / 2) + 1;// + 1
			}
		}
		// [a, #, a, #, a, #, a]
		// [1, 2, 3, 4, 3, 2, 1]
		// 0 1 1 2 1
		// [a, #, b, #, c]
		// [1, 1, 2, 1, 1]
		// [a, #, a, #, a, #, a, #, a, #, a, #, a, #, a, #, a, #, a, #, a, #, a]
		// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
		return ans;
	}

	private char[] sharp(String s) {
		len = s.length();
		sharpLen = (len << 1) - 1;
		char[] ans = new char[sharpLen];
		char[] src = s.toCharArray();
		int p = 0;
		for (int i = 0; i < sharpLen; i++) {
			if ((i & 1) == 0) {
				ans[i] = src[p++];
			} else {
				ans[i] = '#';
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		so.debug5();
	}

}
